const axios = require('axios');
const cheerio = require('cheerio');

// 请求获取轮播图数据
exports.getSwiperList = async () => {
    const url = 'https://api.uomg.com/api/rand.img1?format=json';
    const respList = await Promise.all([
        axios.get(url),
        axios.get(url),
        axios.get(url),
        axios.get(url),
        axios.get(url),
    ]);
    return respList.map(item => item.data.imgurl);
}

// 声明此方法用来获取JSONP数据
const news = data => data.data;

/**
 * 请求获取新闻数据(注：数据来源央视新闻)
 * @param {Number} page 页码
 */
exports.getNewsList = async (page = 1) => {
    let url = `https://news.cctv.com/2019/07/gaiban/cmsdatainterface/page/news_${page}.jsonp?cb=news`;
    let resp = await axios.get(url);
    let data = eval(resp.data);
    return {
        newsList: data.list,
        total: data.total,
        page
    };
}

/**
 * 请求网页链接，提取新闻信息
 * @param {String} url 新闻网页链接
 */
exports.getNewsInfo = async (type = '', id = '')  => {
    // 判断参数 type 与 id 为空
    if (type === '' || id === '' || ['photo', 'news'].indexOf(type) === -1) {
        return { code: 403, message: 'type 或 id 参数为空' };
    }
    // 拼接字符串得到新闻详情网页链接
    let date = new Date();
    let y = date.getFullYear();
    let m = (date.getMonth() + 1).toString().padStart(2, '0');
    let d = date.getDate().toString().padStart(2, '0');
    let url = `https://${type}.cctv.com/${y}/${m}/${d}/${id}.shtml`;
    // 初始化默认数据
    let data = { title: '', source: '', pubdate: '', content: '' };
    let resp = await axios.get(url);
    let $ = cheerio.load(resp.data);
    if (type === 'news') {
        let info = $('#title_area .info').text().split('|');
        data.title = $('#title_area h1').text() || $('.cnt_bd h1').text();
        data.source = info[0] || '来源：' + $('.function .info i a').text();
        data.pubdate = info[1] || $('.function .info i')[0].children[2].data;
        $('#content_area #myFlash').parent().remove();
        $('#text_area #myFlash').parent().remove();
        data.content = $('#content_area').html() || $('#text_area').html();
    } else {
        data.title = $('.bigTitle').text();
        data.source = '来源：' + $('.tj_top .info i').text().trim();
        data.pubdate = $('.tj_top .info span').text();
        // https://photo.cctv.com/2021/02/10/PHOAwD5cllCiWqHPahxgjsEB210210.xml?randomNum=98
        url = url.replace('shtml', 'xml?randomNum=98');
        resp = await axios.get(url);
        $ = cheerio.load(resp.data);
        data.textList = [];
        data.imageList = [];
        $('li').each((_, el) => {
            data.textList.push(el.children[0].data.replace(/(\[|\]|CDATA)/g, ''));
            data.imageList.push($(el).attr('photourl'));
        });
    }
    return data;
}

/**
 * 获取图片列表
 */
exports.getImageList = async function(id) {
    let resp = await axios.get(`https://www.mihuashi.com/api/v1/users/${id}/artworks`); 
    return resp.data.artworks;;
}